import { defineComponent, h, type VNode, type Component, withDirectives, resolveComponent, isVNode } from 'vue'
import { vFocus } from '@v-model/shared--directives'

export interface IconProps {
  is: string
  subOptions: Object
  focus: Boolean
}

export interface SubassemblyModule {
  [key: string]: unknown
}

const CachedList: SubassemblyModule = {}

export default defineComponent({
  name: 'AutoComponents',
  props: {
    is: [String, Object, Function],
    subOptions: Object,
    focus: Boolean,
  },

  render(props: IconProps): () => VNode | null {
    let componentName: string | Function = props.is

    if (!CachedList[componentName]) {
      if (typeof componentName === 'string') {
        CachedList[componentName] = resolveComponent(componentName)
      } else if (typeof componentName === 'object') {
        // 当为自定义组件时，直接返回，不需要 h 函数处理
        // directively return source when target is object or funcion

        CachedList[componentName] = componentName
      } else if (typeof componentName === 'function') {
        // 当传入为渲染函数时
        componentName = componentName as Function
        return componentName()
      }
    }
    // console.log(`output->a,b,c`, attrs)

    const component = CachedList[componentName] as Object

    return h(component, { ...props.subOptions })

    // const subOptions = JSON.parse(JSON.stringify({ ...props.subOptions }))
    // if (subOptions.event) delete subOptions.event
    // // 有 focus 的加载 聚焦指令，没有的则直接加载组件
    // return props.focus ? withDirectives(h(component, subOptions), [[vFocus, props.focus]]) : h(component, subOptions)
  },
})
